package liuliu.throughwaring.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import net.tsz.afinal.annotation.view.CodeNote;

import java.util.List;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.control.add.police.person.IRegPersonView;
import liuliu.throughwaring.control.add.police.person.RegPersonListener;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.CompanyPersonModel;
import liuliu.throughwaring.model.PersonModel;

/**
 * 从业人员管理页面
 * 作者：柳伟杰 on 2016/3/15 17:15
 * 邮箱：1031066280@qq.com
 */
public class CongyeActivity extends BaseActivity implements IRegPersonView {
    public static CongyeActivity mInstance;
    @CodeNote(id = R.id.congye_toolbar)
    TToolbar toolbar;
    @CodeNote(id = R.id.entry_company_name_et)
    AutoCompleteTextView company_name_et;//企业名称
    @CodeNote(id = R.id.entry_person_name_et)
    EditText person_name_et;
    @CodeNote(id = R.id.add_company_name_btn, click = "onClick")
    Button add_company_name;
    @CodeNote(id = R.id.add_person_name_btn, click = "onClick")
    Button add_person_name;
    @CodeNote(id = R.id.no_data_ll, click = "onClick")
    LinearLayout no_data_ll;
    @CodeNote(id = R.id.congye_lv)
    ListView congye_lv;
    private CommonAdapter mAdapter;
    private ArrayAdapter<String> mAAdapter;
    String[] companyNames;//所有公司名称集合
    String[] persons;
    private LLDialog llDialog;
    RegPersonListener mListener;
    String style = "";

    @Override
    public void initViews() {
        setContentView(R.layout.activity_congye);
        mInstance = this;
        style = getIntent().getStringExtra("style");
        switch (style) {
            case "congye":
                toolbar.setLeftTitle("从业人员");
                add_company_name.setText("新增企业");
                company_name_et.setHint("请输入企业信息");
                break;
            case "zulin":
                toolbar.setLeftTitle("租赁人员");
                add_company_name.setText("新增房屋");
                company_name_et.setHint("请输入出租屋信息");
                break;
        }
        llDialog = new LLDialog(this);
        mListener = new RegPersonListener(this, this);
    }

    @Override
    public void initEvents() {
        //返回
        toolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                mInstance.finish();
            }
        });
        List<CompanyModel> list = null;
        switch (style) {
            case "congye":
                list = finalDb.findAllByWhere(CompanyModel.class, "CompanyType='Company'");
                break;
            case "zulin":
                list = finalDb.findAllByWhere(CompanyModel.class, "CompanyType='Lease'");
                break;
        }
        if (list != null) {
            companyNames = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                companyNames[i] = list.get(i).getCompanyName();
            }
            company_name_et.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, companyNames));
            company_name_et.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    loadCompany();
                }
            });
        }
        company_name_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                loadCompany();
            }
        });
        person_name_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                loadCompany();
            }
        });
    }

    /**
     * 页面所有点击事件处理
     *
     * @param view
     */
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_company_name_btn://添加企业
                Intent intent = new Intent();
                intent.setClass(CongyeActivity.this, RegUnitActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("type", style);
                intent.putExtras(bundle);
                startActivityForResult(intent, 0);
                break;
            case R.id.add_person_name_btn://添加人员点击事件
                if (("").equals(company_name_et.getText().toString())) {
                    switch (style) {
                        case "congye":
                            mUtils.ToastShort("请先填写企业信息");
                            break;
                        case "zulin":
                            mUtils.ToastShort("请先填写出租屋信息");
                            break;
                    }
                } else {
                    Intent intents = new Intent();
                    intents.setClass(CongyeActivity.this, RegPersonActivity.class);
                    bundle = new Bundle();
                    bundle.putString("companyName", style + ":" + company_name_et.getText().toString());
                    intents.putExtras(bundle);//将Bundle添加到Intent,也可以在Bundle中添加相应数据传递给下个页面,例如：bundle.putString("abc", "bbb");
                    startActivityForResult(intents, 0);// 跳转并要求返回值，0代表请求值(可以随便写)
                }
                break;
        }
    }

    /**
     * 根据公司名称与人员名称，查询出人员信息并显示。
     * 1.从业人员 Company
     * 2.流动人员 Free
     * 3.租赁人员 Lease
     */
    private void loadCompany() {
        switch (style) {
            case "congye":
                //查找出所有在职人员信息(根据创建时间倒序排列)
                final List<PersonModel> person = finalDb.findAllByWhere(PersonModel.class, "PersonComapnyType='Company' and PersonComapnyName='" + company_name_et.getText().toString()
                        + "' and PersonName like '%" + person_name_et.getText().toString() + "%' and PersonStatus not in ('LeaveJob')  order by PersonCreateTime desc");
                if (person != null) {
                    if (person.size() > 0) {
                        persons = new String[person.size()];
                        for (int i = 0; i < person.size(); i++) {
                            persons[i] = person.get(i).getPersonName();
                        }

                        mAdapter = new CommonAdapter<PersonModel>(mInstance, person, R.layout.item_congye) {
                            @Override
                            public void convert(ViewHolder holder, final PersonModel personModel, int position) {
                                holder.setText(R.id.user_name_tv_congye, personModel.getPersonName());
                                switch (personModel.getPersonStatus()) {
                                    case "OnJob":
                                        holder.setText(R.id.user_state_tv_congye, "在职");
                                        break;
                                    default:
                                        holder.setText(R.id.user_state_tv_congye, "离职");
                                        break;
                                }
                                holder.setText(R.id.user_unit_tv_congye, personModel.getPersonComapnyName());
                                holder.setText(R.id.create_time_tv_congye, personModel.getPersonCreateTime().split(" ")[0]);
                                holder.setOnClickListener(R.id.edit_btn_congye, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        llDialog.setMiddleMessage("确认要离职？");
                                        llDialog.setOnPositiveListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {//通知后台给置顶人员离职
                                                personModel.setCheckInTime(Utils.getDateString(personModel.getCheckInTime()));
                                                personModel.setCheckOutTime(personModel.getCheckInTime());
                                                personModel.setPersonStatus("LeaveJob");
                                                mListener.RegPerson(personModel);
                                                llDialog.dismiss();
                                            }
                                        });
                                        llDialog.setOnNegativeListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                llDialog.cancel();
                                            }
                                        });
                                        llDialog.show();
                                    }
                                });
                            }
                        };
                        congye_lv.setAdapter(mAdapter);
                        congye_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                                Intent intents = new Intent();
                                intents.setClass(CongyeActivity.this, PersonDetailActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("personid", person.get(position).getPersonId());
                                intents.putExtras(bundle);//将Bundle添加到Intent,也可以在Bundle中添加相应数据传递给下个页面,例如：bundle.putString("abc", "bbb");
                                startActivityForResult(intents, 1);// 跳转并要求返回值，0代表请求值(可以随便写)
                            }
                        });
                        congye_lv.setVisibility(View.VISIBLE);
                        no_data_ll.setVisibility(View.GONE);
                    } else {
                        congye_lv.setVisibility(View.GONE);
                        no_data_ll.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case "zulin":
                //查找指定出租屋的所有租赁人员信息
                final List<PersonModel> zulin = finalDb.findAllByWhere(PersonModel.class, "PersonComapnyType='Lease' and PersonComapnyName='" + company_name_et.getText().toString()
                        + "' and PersonName like '%" + person_name_et.getText().toString() + "%' and PersonStatus not in ('CheckOut')  order by PersonChangeTime desc");
                if (zulin != null) {
                    if (zulin.size() > 0) {
                        persons = new String[zulin.size()];
                        for (int i = 0; i < zulin.size(); i++) {
                            persons[i] = zulin.get(i).getPersonName();
                        }
                        mAdapter = new CommonAdapter<PersonModel>(mInstance, zulin, R.layout.item_zulin) {
                            @Override
                            public void convert(ViewHolder holder, final PersonModel personModel, int position) {
                                holder.setText(R.id.user_name_tv_zulin, personModel.getPersonName());
                                switch (personModel.getPersonSex()) {
                                    case "1":
                                        holder.setText(R.id.user_sax_tv_zulin, "男");
                                        break;
                                    case "2":
                                        holder.setText(R.id.user_sax_tv_zulin, "女");
                                        break;
                                }
                                holder.setText(R.id.user_address_tv_zulin, personModel.getPersonAddress());
                                holder.setText(R.id.create_time_tv_zulin, personModel.getPersonCreateTime());
                                holder.setOnClickListener(R.id.edit_btn_zulin, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        llDialog.setMiddleMessage("确认要退租？");
                                        llDialog.setOnPositiveListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {//通知后台给置顶人员离职
                                                personModel.setCheckInTime(Utils.getDateString(personModel.getCheckInTime()));
                                                personModel.setCheckOutTime(personModel.getCheckInTime());
                                                personModel.setPersonStatus("CheckOut");
                                                mListener.RegPerson(personModel);
                                            }
                                        });
                                        llDialog.setOnNegativeListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                llDialog.cancel();
                                            }
                                        });
                                        llDialog.show();
                                    }
                                });
                            }
                        };
                        congye_lv.setAdapter(mAdapter);
                        congye_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                                mUtils.IntentPost(PersonDetailActivity.class, new Utils.putListener() {
                                    @Override
                                    public void put(Intent intent) {
                                        intent.putExtra("personid", zulin.get(position).getPersonId());
                                    }
                                });
                            }
                        });
                        congye_lv.setVisibility(View.VISIBLE);
                        no_data_ll.setVisibility(View.GONE);
                    } else {
                        congye_lv.setVisibility(View.GONE);
                        no_data_ll.setVisibility(View.VISIBLE);
                    }
                    break;
                }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        loadCompany();//添加成功
        if (resultCode == 131) {
            mUtils.ToastShort("添加成功~~");
        } else if (resultCode == 132) {
            mUtils.ToastShort("已离职~~");
        } else if (resultCode == 133) {
            mUtils.ToastShort("已离店~~");
        }
    }

    @Override
    public void onRegPersonResult(boolean isTrue, String mes) {
        if (isTrue) {
            mUtils.ToastShort("离职成功！");
            loadCompany();
        } else {
            mUtils.ToastShort("离职失败，请重新操作~~");
        }
    }
}
